limsMaterial.editPage = {

    getGridParam: function () {
        var _this = this
        return {
            type: 'grid',
            id: _this.idManager.materialGrid,
            url: _this.urlManager.materialGrid + '/queries',
            service: 'limsMaterialServiceImpl',
            dbTable: 'T_LIMS_MATERIAL',
            columns: limsMaterial.getEditListColumns(),
            onLoadSuccess: function (data) {
                if (!Gikam.isEmpty(data)) {
                    this.activeRowByIndex(0)
                } else {
                    _this.refreshTabs(null)
                }
            },
            deleteFormatter: function (row) {
                return row.matCode
            },
            onRowActive: function (index, row) {
                _this.refreshTabs(row)
            },
            onCellClick: function (field, row) {
                field === 'matCode' && _this.editMaterial(row)
            },
            page: true,
            toolbar: [{
                type: 'button',
                text: 'GIKAM.BUTTON.INSERT',
                icon: 'add',
                onClick: function () {
                    Gikam.preInsert({
                        modalTitle: 'BASEMODULE.RM.MATERIALS.MODAL.ADD',
                        fields: limsMaterial.getBaseInfoFormFields(),
                        url: _this.urlManager.materialGrid,
                        disableNotEmptyValidate: true,
                        columns: 2,
                        width: 800,
                        height: 370
                    }).done(function (id) {
                        Gikam.getComp(_this.idManager.materialGrid).refresh()
                    })
                }
            }, {
                type: 'button',
                text: 'GIKAM.BUTTON.DELETE',
                icon: 'remove-row',
                onClick: function () {
                    Gikam.getComp(_this.idManager.materialGrid).deleteRows(_this.urlManager.materialGrid)
                }
            }, {
                type: 'button',
                text: 'GIKAM.BUTTON.EXPORT_TEMPLATE',
                icon: 'export',
                onClick: function () {
                    Gikam.getText(IFM_CONTEXT + '/core/module/item/files/template-urls' + Gikam.param({
                        templateCode: 'LimsMaterialExportTemplate',
                        service: 'LimsMaterialExportTemplate'
                    })).done(function (url) {
                        Gikam.download(url)
                    })
                }
            }, {
                type: 'button',
                text: 'GIKAM.BUTTON.IMPORT',
                icon: 'upload',
                onClick: function () {
                    Gikam.create('simpleUploader', {
                        id: 'mt-info-import',
                        dbTable: 'T_LIMS_MATERIAL',
                        autoClose: true,
                        multiple: false,
                        onAfterClose: function (fields) {
                            if (Gikam.isNotEmpty(fields)) {
                                workspace.window.showMask()
                                var url = Gikam.printf(IFM_CONTEXT + '/core/module/item/files/{id}/action/import/' + 'LimsMaterialImportFileFunction', {
                                    id: fields[0].id
                                })
                                Gikam.post(url).done(function (req) {
                                    Gikam.getComp(_this.idManager.materialGrid).refresh()
                                    if (req.message) {
                                        Gikam.alert(req.message)
                                    }
                                    if (req.url) {
                                        Gikam.download(req.url);
                                    }
                                }).always(function () {
                                    workspace.window.closeMask()
                                })
                            }
                        }
                    })
                }
            },]
        }
    },

    editMaterial: function (row) {
        let _this = this
        Gikam.createLimsModal({
            title: 'GIKAM.BUTTON.EDIT',
            width: 800,
            height: 370,
            onConfirm: function () {
                var form = Gikam.getComp('material-edit-form')
                if (form.validate()) {
                    var data = form.getData()
                    data.id = row.id
                    var chooseData = []
                    Gikam.put(_this.urlManager.materialGrid + '/instant', Gikam.getJsonWrapper(null, [null, chooseData])).done(function () {
                        Gikam.getComp(_this.idManager.materialGrid).refreshRowById(row.id)
                    })
                    Gikam.getLastModal().close(data);
                }
            },
            m: {
                type: 'form',
                id: 'material-edit-form',
                titleWidth: 100,
                url: Gikam.printf(_this.urlManager.materialGrid + '/{id}', {id: row.id}),
                fields: limsMaterial.getEditInfoFormFields(),
                disableNotEmptyValidate: true,
                columns: 2,
                // width: 800,
                // height: 400,
                onRendered: function () {
                    this.toFieldsReadonly(['matCode'])
                }
            },
        })
    },

    refreshTabs: function (row) {
        let _this = this
        Gikam.getAsyncComp(_this.idManager.inventoryGrid).done(grid => {
            if (row && row.id) {
                grid.refresh({
                    url: _this.urlManager.inventoryGrid + '/queries',
                    requestData: {
                        matCode_EQ: row.matCode
                    }
                })
            } else {
                grid.refresh({
                    url: _this.urlManager.inventoryGrid + '/queries',
                    requestData: {
                        matCode_EQ: -1
                    }
                })
            }
        })
    },

    getBaseInfoTab: function () {
        var _this = this
        return {
            type: 'tab',
            panels: [{
                title: 'BASEMODULE.RM.MATERIALS.TAB.BASE_INFO',
                items: [{
                    type: 'form',
                    service: 'limsMaterialServiceImpl',
                    dbTable: 'T_LIMS_MATERIAL',
                    id: 'lims-material-edit-list-base-info-form',
                    fields: limsMaterial.getBaseInfoFormFields(),
                    onUpdated: function () {
                        var grid = Gikam.getComp('lims-material-edit-list-grid')
                        grid.refreshRowById(grid.getActivedRow().id)
                    },
                }]
            }]
        }
    },

    getInventoryTab: function () {
        let _this = this
        return {
            type: 'tab',
            panels: [{
                title: 'T_LIMS_STANDARD_INVENTORY.SERVICE_NAME',
                items: [{
                    type: 'grid',
                    id: _this.idManager.inventoryGrid,
                    service: 'limsStandardInventoryServiceImpl',
                    dbTable: 'T_LIMS_STANDARD_INVENTORY',
                    columns: limsMaterial.getStandardInventoryEditListColumns(),
                    onLoadSuccess: function (data) {
                        if (!Gikam.isEmpty(data)) {
                            this.activeRowByIndex(0)
                        } else {
                            _this.refreshAttachments(_this.idManager.inventoryGrid)
                            _this.refreshHistory(null)
                        }
                    },
                    deleteFormatter: function (row) {
                        return row.storageNo || row.id
                    },
                    onRowActive: function (index, row) {
                        _this.refreshAttachments(_this.idManager.inventoryGrid)
                        _this.refreshHistory(row)
                    },
                    onUpdated: function () {
                        var grid = Gikam.getComp(_this.idManager.inventoryGrid);
                        grid.refreshRowById(grid.getActivedRow().id)
                    },
                    toolbar: [{
                        type: 'button',
                        text: 'GIKAM.BUTTON.INSERT',
                        icon: 'add',
                        onClick: function () {
                            let mateGrid = Gikam.getComp(_this.idManager.materialGrid)
                            let actRow = mateGrid.getActivedRow()
                            if (Gikam.isEmpty(actRow)) {
                                Gikam.alert('GIKAM.TIP.CHOOSE_AT_LEAST_ONE_ITEM')
                                return
                            }
                            if (!actRow.matCode || actRow.matCode === '') {
                                Gikam.alert('BASEMODULE.RM.MATERIALS.TIP.MATCODE_IS_NULL')
                                return
                            }
                            if (!actRow.status || actRow.status === '0') {
                                Gikam.alert('BASEMODULE.RM.MATERIALS.TIP.STATUS_IS_DISABLE')
                                return
                            }
                            Gikam.createLimsModal({
                                title: 'BASEMODULE.RM.MATERIALS.MODAL.ADD',
                                width: 800,
                                height: 420,
                                onConfirm: function () {
                                    var form = Gikam.getComp('insert-inventory-form');
                                    if (form.validate()) {
                                        let data = form.getData();
                                        var warrantyExpiryDate = new Date(data.warrantyExpiryDate)
                                        var usefulTime = new Date(data.usefulTime)

                                        if (warrantyExpiryDate > usefulTime) {
                                            Gikam.alert('BASEMODULE.RM.MATERIALS.TIP.WARRANTYEXPIRYDATE_BEYOND_USEFULTIME')
                                            return
                                        }

                                        workspace.window.showMask();
                                        let url = _this.urlManager.inventoryGrid
                                        Gikam.postText(url, Gikam.getJsonWrapper({}, [null, [data]])).done(req => {
                                            Gikam.getComp(_this.idManager.inventoryGrid).refresh()
                                            mateGrid.refreshRowById(actRow.id)
                                        }).always(function () {
                                            Gikam.getLastModal().close()
                                            workspace.window.closeMask()
                                        });
                                    }
                                },
                                m: {
                                    type: 'form',
                                    id: 'insert-inventory-form',
                                    fields: limsMaterial.getStandardInventoryBaseInfoFormFields(),
                                    columns: 2,
                                    disableNotEmptyValidate: true,
                                    onRendered: function () {
                                        this.setData({
                                            matCode: actRow.matCode
                                        })
                                    }
                                }
                            })
                        }
                    }, {
                        type: 'button',
                        text: 'GIKAM.BUTTON.DELETE',
                        icon: 'remove-row',
                        onClick: function () {
                            let mateGrid = Gikam.getComp(_this.idManager.materialGrid)
                            let actRow = mateGrid.getActivedRow()
                            if (Gikam.isEmpty(actRow)) {
                                Gikam.alert('GIKAM.TIP.CHOOSE_AT_LEAST_ONE_ITEM')
                                return
                            }
                            Gikam.getComp(_this.idManager.inventoryGrid).deleteRows(_this.urlManager.inventoryGrid).done(function () {
                                mateGrid.refreshRowById(actRow.id)
                            })
                        }
                    }, {
                        type: 'button',
                        text: 'BASEMODULE.RM.MATERIALS.BUTTON_CHECKOUT',
                        icon: 'export',
                        onClick: function () {
                            var materialGrid = Gikam.getComp(_this.idManager.materialGrid)
                            var materialActivedRow = materialGrid.getActivedRow()
                            if (Gikam.isEmpty(materialActivedRow)) return
                            /*                            if (materialActivedRow.forbidden == '0') {
                                                            Gikam.alert('THIS.MATERIAL.DISABLE.USED')
                                                            return
                                                        }*/
                            if (!materialActivedRow.status || materialActivedRow.status === '0') {
                                Gikam.alert('BASEMODULE.RM.MATERIALS.TIP.STATUS_IS_DISABLE')
                                return
                            }
                            var grid = Gikam.getComp(_this.idManager.inventoryGrid)
                            var activedRow = grid.getActivedRow()
                            if (Gikam.isEmpty(activedRow)) return

                            if (!activedRow.ext$.matexpired || activedRow.ext$.matexpired === '1') {
                                Gikam.alert('BASEMODULE.RM.MATERIALS.TIP.USEFULTIME_PASSED')
                                return
                            }

                            var model = Gikam.create('modal', {
                                title: 'BASEMODULE.RM.MATERIALS.BUTTON_CHECKOUT',
                                height: '250',
                                width: '400',
                                onAfterClose: function (data) {
                                    if (Gikam.isEmpty(data)) {
                                        return
                                    }
                                }
                            })
                            Gikam.create('layout', {
                                renderTo: model.window.$dom,
                                center: {
                                    items: [{
                                        type: 'form',
                                        id: 'insert-checkout-form',
                                        titleWidth: 70,
                                        fields: limsMaterial.getStandardInventoryOutFields(true),
                                        columns: 1,
                                        onLoadSuccess: function () {
                                        }
                                    }, {
                                        type: 'btnToolbar',
                                        items: [{
                                            type: 'button',
                                            text: 'GIKAM.BUTTON.CONFIRM',
                                            class: 'blue',
                                            icon: 'save',
                                            color: 'white',
                                            onClick: function () {
                                                var form = Gikam.getComp('insert-checkout-form')
                                                if (form.validate()) {
                                                    var data = form.getData()
                                                    var url = _this.urlManager.inventoryGrid + '/standards/checkout'
                                                    data.ext$.isoutoperation = 'yes'
                                                    Gikam.postText(url, Gikam.getJsonWrapper(null, [null, [activedRow]], [null, [data]])).done(function (data) {
                                                        materialGrid.refreshRowById(materialActivedRow.id)
                                                        grid.refreshRowById(activedRow.id)
                                                        _this.refreshHistory(activedRow)
                                                        Gikam.getLastModal().close(data)
                                                    })
                                                }
                                            }
                                        }, {
                                            type: 'button',
                                            text: 'GIKAM.BUTTON.CANCEL',
                                            icon: 'back',
                                            onClick: function () {
                                                Gikam.getLastModal().close()
                                            }
                                        }]
                                    }]
                                }
                            })
                        }
                    }, {
                        type: 'button',
                        text: 'BASEMODULE.RM.MATERIALS.BUTTON_INVENTORY',
                        icon: 'refresh',
                        onClick: function () {
                            var materialGrid = Gikam.getComp(_this.idManager.materialGrid)
                            var materialActivedRow = materialGrid.getActivedRow()
                            if (Gikam.isEmpty(materialActivedRow)) return
                            /*                            if (materialActivedRow.forbidden == '0') {
                                                            Gikam.alert('BASEMODULE.RM.MATERIALS.DISABLE.USED')
                                                            return
                                                        }*/
                            if (!materialActivedRow.status || materialActivedRow.status === '0') {
                                Gikam.alert('BASEMODULE.RM.MATERIALS.TIP.STATUS_IS_DISABLE')
                                return
                            }
                            var grid = Gikam.getComp(_this.idManager.inventoryGrid)
                            var activedRow = grid.getActivedRow()
                            if (Gikam.isEmpty(activedRow)) return
                            var model = Gikam.create('modal', {
                                title: 'BASEMODULE.RM.MATERIALS.T_LIMS_STANDARD_INVENTORY.MODAL_INVENTORY',
                                height: '250',
                                width: '400',
                                onAfterClose: function (data) {
                                    if (Gikam.isEmpty(data)) {
                                        return
                                    }
                                }
                            })
                            Gikam.create('layout', {
                                renderTo: model.window.$dom,
                                center: {
                                    items: [{
                                        type: 'form',
                                        id: 'insert-inventory-form',
                                        titleWidth: 70,
                                        fields: limsMaterial.getInventoryFormFields(),
                                        columns: 1,
                                        onLoadSuccess: function () {
                                        }
                                    }, {
                                        type: 'btnToolbar',
                                        items: [{
                                            type: 'button',
                                            text: 'GIKAM.BUTTON.CONFIRM',
                                            class: 'blue',
                                            icon: 'save',
                                            color: 'white',
                                            onClick: function () {
                                                var form = Gikam.getComp('insert-inventory-form')
                                                if (form.validate()) {
                                                    var data = form.getData()
                                                    var url = _this.urlManager.inventoryGrid + '/standards/inventory'
                                                    Gikam.postText(url, Gikam.getJsonWrapper(null, [null, [activedRow]], [null, [data]])).done(function (data) {
                                                        materialGrid.refreshRowById(materialActivedRow.id)
                                                        grid.refreshRowById(activedRow.id)
                                                        _this.refreshHistory(activedRow)
                                                        Gikam.getLastModal().close(data)
                                                    })
                                                }
                                            }
                                        }, {
                                            type: 'button',
                                            text: 'GIKAM.BUTTON.CANCEL',
                                            icon: 'back',
                                            onClick: function () {
                                                Gikam.getLastModal().close()
                                            }
                                        }]
                                    }]
                                }
                            })
                        }
                    }]
                }]
            }]
        }
    },

    getHistoryTab: function () {
        let _this = this
        return {
            type: 'tab',
            panels: [{
                title: 'T_LIMS_STANDARD_HISTORY.SERVICE_NAME',
                items: [{
                    type: 'grid',
                    id: _this.idManager.historyGrid,
                    service: 'limsStandardHistoryServiceImpl',
                    dbTable: 'T_LIMS_STANDARD_HISTORY',
                    columns: limsMaterial.getStandardHistoryEditListColumns(),
                    onLoadSuccess: function (data) {
                        if (!Gikam.isEmpty(data)) {
                            this.activeRowByIndex(0)
                        } else {
                        }
                    },
                    onRowActive: function (index, row) {
                    },
                    toolbar: []
                }]
            }, {
                title: 'GIKAM.FILE.ATTACHMENT',
                items: [_this.getAttachmantStruct(_this.idManager.inventoryGrid, 'T_LIMS_STANDARD_INVENTORY')]
            },]
        }
    },

    refreshHistory: function (row) {
        let _this = this
        Gikam.getAsyncComp(_this.idManager.historyGrid).done(grid => {
            if (row && row.id) {
                grid.refresh({
                    url: _this.urlManager.historyGrid + '/queries',
                    requestData: {
                        standardInventoryId_EQ: row.id
                    }
                })
            } else {
                grid.refresh({
                    url: _this.urlManager.historyGrid + '/queries',
                    requestData: {
                        standardInventoryId_EQ: -1
                    }
                })
            }
        })
    },

    getAttachUploaderId: function (gridId) {
        return gridId + '-uploader'
    },

    refreshAttachments: function (gridId) {
        let _this = this
        let grid = Gikam.getComp(gridId)
        let actRow = grid.getActivedRow()
        Gikam.getAsyncComp(_this.getAttachUploaderId(gridId)).done(uploader => {
            if (actRow && actRow.id) {
                uploader.setOptions({
                    bizId: actRow.id,
                })
            } else {
                uploader.setOptions({
                    bizId: -1,
                })
            }
        })
    },

    getAttachmantStruct: function (gridId, dbTable) {
        let _this = this
        return {
            type: 'uploader',
            immediateUpload: true,
            id: _this.getAttachUploaderId(gridId),
            dbTable: dbTable,
            filter: false,
            genericQuery: false,
            onBeforeUpload: function () {
                var activedRow = Gikam.getComp(gridId).getActivedRow()
                if (Gikam.isEmpty(activedRow)) {
                    Gikam.alert('GIKAM.TIP.CHOOSE_AT_LEAST_ONE_ITEM', 200)
                    return false
                }
            },
        }
    },

    idManager: {
        materialGrid: 'lims-material-edit-list-grid',
        inventoryGrid: 'lims-standard-inventory-edit-list-grid',
        historyGrid: 'lims-standard-history-edit-list-grid'
    },

    urlManager: {
        materialGrid: limsMaterial.baseUrl,
        inventoryGrid: IFM_CONTEXT + '/secure/basemodule/rm/standard-inventorys',
        historyGrid: IFM_CONTEXT + '/secure/basemodule/rm/standard-historys'
    },

    create: function () {
        let _this = this
        Gikam.create('layout', {
            id: 'lims-material-edit-list-layout',
            renderTo: workspace.window.$dom,
            north: {
                height: '45%',
                items: [_this.getGridParam()]
            },
            west: {
                width: '50%',
                items: [_this.getInventoryTab()]
            },
            center: {
                items: [_this.getHistoryTab()]
            }
        })
    },

    init: function () {
        this.create()
    }
}
